package org.kwisatz.proxybot.filters;

import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.httpclient.methods.GetMethod;
import org.kwisatz.proxybot.HttpQueryFilter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Google extends HttpQueryFilter
{
	private NodeList buffer;
	private boolean calculator;

	public Google()
	{
		super("google");
	}
	
	/** test */
	public static void main(String[] args)
	{
		try
		{
			PrintWriter pw=new PrintWriter(System.out);			
			new Google().handleQuery("cos(pi)", pw);
			new Google().handleQuery("0x7d3 in decimal", pw);
			new Google().handleQuery("irc", pw);
			new Google().handleQuery("france", pw);			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	protected void handleQuery(String arguments, PrintWriter out)
	{
		try
		{
			String s=URLEncoder.encode(arguments, "UTF-8");
			GetMethod get = new GetMethod("http://www.google.com/search?q="+s);			
			httpClient.executeMethod(get);
			
			Document document = parseDOM(get.getResponseBodyAsStream());
			buffer = (NodeList) xpath.evaluate("//li[@class='g']",
				document, XPathConstants.NODESET);
			calculator = handleCalculator(document, out); 
			if(!calculator)
				handleContinue(0, out);
			out.flush();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

	private boolean handleCalculator(Document document, PrintWriter out)
		throws XPathExpressionException
	{
		Node n = (Node) xpath.evaluate(
			"//img[@src='/images/calc_img.gif']",
			document, XPathConstants.NODE);
		if(n!=null)
		{
			Node td=n.getParentNode().getNextSibling().getNextSibling();
			out.println(getTextString(td));
			return true;
		}
		else
			return false;
	}
	
	@Override
	protected void handleContinue(int index, PrintWriter out)
	{
		try
		{
			if(calculator)
				index -- ;
			if(index>=buffer.getLength())
				return;
			Element div=(Element) buffer.item(index);			
			Element a=(Element) xpath.evaluate("//a[@class='l']", div, XPathConstants.NODE);
			Element font=(Element) xpath.evaluate("//div[@class='s']", div,
				XPathConstants.NODE);
			Element span=(Element) xpath.evaluate("//span[@class='gl']",
				div, XPathConstants.NODE);
	
			String descr="";
			Node nn=font.getFirstChild();
			
			while(nn!=null && !nn.equals(span))
			{
				descr+=getTextString(nn);
				nn=nn.getNextSibling();
			}
			String url=a.getAttribute("href");
			String title=getTextString(a);
			
			out.println(url + " (" + title + ") => " + descr);
			out.flush();
		}
		//catch everything so the filter never crash
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}
